package com.tianqizhikong.exceltool;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *@Author: zlr
 *@CreateTime: 2024-12-27
 *@Description:
 */

public class CustomIntegerConverter implements Converter<Integer> {

    private static final Logger logger = LoggerFactory.getLogger(CustomIntegerConverter.class);
    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
        if (context == null || context.getValue() == null) {
            return new WriteCellData<>(CellDataTypeEnum.NUMBER, "");
        }
        return new WriteCellData<>(CellDataTypeEnum.NUMBER, context.getValue().toString());
    }

    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (cellData == null || cellData.getStringValue() == null || cellData.getStringValue().trim().isEmpty()) {
            return null; // 或者返回默认值 0
        }
        try {
            return Integer.parseInt(cellData.getStringValue().trim());
        } catch (NumberFormatException e) {
            logger.error("转换失败: {}", cellData.getStringValue(),e);
            return null; // 或者返回默认值 0
        }
    }
}

